#!/usr/bin/python3
import redis
import secrets
import datetime
import mysql.connector

from flask import Flask, Blueprint, request, jsonify, render_template



# 数据库暂时采用csv,以后用mysql
class FTunDB:
    def __init__(self):
        self.r = None
        pass
    
    
    def add(self, data={"token": "", "start":"", "end": "1"}):
        pass
    #  
    def create(self):
        cnx = mysql.connector.connect(user='llg', password='llgpwd123', host='127.0.0.1')

        cursor = cnx.cursor()

        query = 'CREATE DATABASE ftun'
        cursor.execute(query)

    def add_new(self, detla={"day":0, "sec": 60, "ower": "no"}):
        current_time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        current_time = datetime.datetime.strptime(current_time_str, "%Y-%m-%d %H:%M:%S")
        token = secrets.token_hex(32)
        tm_start = current_time;
        tm_end = current_time + datetime.timedelta(
            days=detla["day"],
            seconds=detla["sec"])
        # 构建表数据
        print(f'{token} {tm_start} {tm_end} {True}')

        # 数据库操作
        cnx = mysql.connector.connect(user='dbcmd1', password='pwd123', host='localhost', database='db_ftun')
        cursor = cnx.cursor()

        # 执行SQL语句
        insert_query = "INSERT INTO tb_token (token, tm_start, tm_end, ower) VALUES (%s, %s, %s, %s)"
        cursor.execute(insert_query, (token, tm_start, tm_end, detla['ower']))
        cnx.commit()

        cursor.close()
        cnx.close()
        return token;

    def select(self):
        cnx = mysql.connector.connect(user='dbcmd1', password='pwd123', host='localhost', database='db_ftun')
        cursor = cnx.cursor()

        # 执行SQL语句
        query = "SELECT * FROM tb_token"
        cursor.execute(query)
        # cnx.commit()

        result = cursor.fetchall()

        # 打印结果
        rows = [row for row in result]
        # cursor.close()
        cnx.close()
        return rows
        pass
    def remove(self, db=0, port=6379):
        # self.r = redis.Redis(host='localhost', port=6379, db=db)
        pass
    # 某token是否存在

class SyncSQL:
    def __init__(self):
        pass
    def mysql_to_redis(self, data, db=0):
        # 定义两个日期时间字符串
        r = redis.Redis(host='localhost', port=6379, db=0)
        for row in data:
            start_time = str(row[2])
            end_time   = str(row[3])

            # 转换为datetime对象
            current_time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            current_time = datetime.datetime.strptime(current_time_str, "%Y-%m-%d %H:%M:%S")
            start_datetime = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
            end_datetime = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')

            time_delta = (end_datetime - current_time).total_seconds()
            time_delta = max(time_delta, 1) # 如果时间戳是0, setex则会出错
            r.setex(row[1], int(time_delta), "1")

db_r = Blueprint('db', __name__)

@db_r.route('/db/init', methods=['GET'])
def init():
    print("reload DB");
    db = FTunDB()
    # 启动时候默认添加3天试用
    rows = db.select();

    sync = SyncSQL()
    sync.mysql_to_redis(rows)
    

    return jsonify({
        'message': '-',
        'success': True,
    })

@db_r.route('/db/new_token', methods=['POST'])
def new_token():
    print("add DB");
    data = request.json

    if not all(key in data for key in ['token', 'day', 'sec', 'ower']):
        print("error")
        return jsonify({
            'message': '数据错误',
            'success': False,
        })
    
    db = FTunDB()
    detla = {
        "day": data.get('day'),
        "sec": data.get("sec"),
        "ower": data.get("ower"),
    }
    token = db.add_new(detla)
    rows = db.select();

    sync = SyncSQL()
    sync.mysql_to_redis(rows)
    

    return jsonify({
        'message': '-',
        'success': True,
        'val':token,
    })



@db_r.route('/db/login', methods=['POST'])
def new_login():

    if not all(key in data for key in ['token', 'user', 'password']):
        print("error")
        return jsonify({
            'message': '数据错误',
            'success': False,
        })

    
def _test():
    db = FTunDB()
    detla = {
        "day":0.1,
        "sec": 320
    }
    # db.add_new(detla)
    rows = db.select();
    # for row in rows:
    #     print(type(row[1]), row[2])
    
    sync = SyncSQL()
    sync.mysql_to_redis(rows)
    pass

if __name__ == '__main__':
    _test();
# 